package com.ldg.crm.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ldg.crm.common.CommonResult;
import com.ldg.crm.dto.UserDto;
import com.ldg.crm.entity.UserEntity;
import com.ldg.crm.service.EmployeeService;

@Controller
@RequestMapping("/user")
public class UserController {

	@Autowired
	EmployeeService employeeService;

	@RequestMapping(value = "list")
	@ResponseBody
	public UserDto findUserAll(@RequestParam(value = "page", required = false, defaultValue = "1") int pageNum,
			@RequestParam(value = "rows", required = false, defaultValue = "20") int pageSize) {

		return employeeService.findPageList1(pageNum, pageSize);
	}

	@RequestMapping("add")
	@ResponseBody
	public CommonResult<UserEntity> addEmployee(UserEntity employee) {

		CommonResult<UserEntity> result = null;
		
		if (employeeService.addUser(employee) == 1) {
			result = CommonResult.success(employee, "添加员工操作 成功！");
		} else{
			result = CommonResult.failed("该员工已存在！");
		}

		return result;
	}

	@RequestMapping("modif")
	@ResponseBody
	public CommonResult<UserEntity> modifEmployee(UserEntity employee) {
		System.err.println(employee);

		CommonResult<UserEntity> result = null;

		if (employeeService.updateUser(employee) == 1) {
			result = CommonResult.success("修改员工操作 成功！");
		} else {
			result = CommonResult.failed("修改员工操作 失败！");
		}

		return result;
	}

	@RequestMapping("remove")
	@ResponseBody
	public CommonResult<UserEntity> removeEmployee(Integer[] ids) {
		CommonResult<UserEntity> result = null;

		if (employeeService.deleteUser(ids) > 0) {
			result = CommonResult.success("删除员工操作 成功！");
		} else {
			result = CommonResult.failed("删除员工操作 失败！");
		}

		return result;
	}

	/***
	 * 增加用户
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "login")
	@ResponseBody
	public String login(UserEntity user, HttpSession session) {

		// 数据库查询登录
		UserEntity loginUser = employeeService.findByNumberAndPassword(user);

		// 判断是否为空
		if (loginUser != null) {
			// 登录成功跳转到欢迎页
			session.setAttribute("loginUser", user);
			return "success";
		} else {
			// 为空，登录失败，继续登录
			return "error";
		}

	}

	@RequestMapping(value = "logOut")
	@ResponseBody
	public String logOut(HttpServletRequest request) {

		HttpSession session = request.getSession();

		if (session != null) {
			session.invalidate();
			return "success";
		} else {
			return "error";
		}
	}

}
